# -*- coding : utf-8 -*-

from PySide2.QtWidgets import QApplication, QMainWindow, QHeaderView, QMessageBox, QTableWidgetItem
from PySide2.QtCore import Qt, QThread, Signal
from PySide2.QtGui import QFont

import sys
import time
import json


from ui.ui_mdi_note_list import Ui_MainWindow
from windows.update_note import UpdateNoteWindow

class MdiHomeWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, session, parent=None):
        self.parent = parent
        super().__init__()
        self.session = session
        
        self.url_note_del = "http://127.0.0.1:8008/note/del/?id={id}"
        self.task_flag = True
        self.task_get = None
        self.note_data = None
        
        self.setupUi(self)
        self.init_page()
        
        self.url_note_get = 'http://127.0.0.1:8008/note/getnotes/?query=1'
        self.task_del_flag = True
        self.task_del = None
        
        self.action_flush.triggered.connect(self.start_get_note_data)
        self.tableWidget.cellClicked.connect(self.tableWidget_clicked)

    def init_page(self):
        self.tableWidget.setColumnCount(6)
        self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) # 水平自适应
        self.tableWidget.verticalHeader().setSectionResizeMode(QHeaderView.Stretch) # 垂直自适应]
        self.tableWidget.setHorizontalHeaderLabels(["ID", "标题", "创建时间", "更新时间", "修改", "删除"])
        self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
    
    def start_get_note_data(self, check=None):
        
        if not self.task_flag:
            return
        
        self.task_get = GetNoteData(self.session, self.url_note_get)
        self.task_get.signalData.connect(self.task_get_signal_dict)
        self.task_get.start()
        self.task_flag = False
    
    
    def update_page(self):
        
        self.tableWidget.clearContents() # 清空表格内容
        data_len = len(self.note_data)
        self.tableWidget.setRowCount(data_len)
        
        note = None
        for row in range(data_len):
            note = self.note_data[row]
            self.parent.loginfo.appendPlainText(str(note))
            for column in range(6):            
                item = QTableWidgetItem() 
                item.setTextAlignment(Qt.AlignHCenter| Qt.AlignVCenter) # 文本显示位置
                item.setFont(QFont("微软雅黑", 12, QFont.Black)) # 设置字体
                self.tableWidget.setItem(row, column, item)
                self.__set_item_text(note, column, item)
                
                
                
        
        self.task_flag = True
    
    def __set_item_text(self, note, pos, item):

        text = None
        if pos == 0:
            text = str(note['pk'])
        elif pos == 1:
            text = note['fields']['title']
        elif pos == 2:
            text = note['fields']['create_time']
        elif pos == 3:
            text = note['fields']['update_time']
        elif pos == 4:
            text = '修改内容'
        elif pos == 5:
            text = '删除'
        item.setText(text)
    
    def tableWidget_clicked(self, x, y):
        
        if y == 5:
            _id = self.tableWidget.item(x, 0).text()
            if not self.task_del_flag:
                return
        
            self.task_del = DelNoteData(self.session, self.url_note_del.format(id=_id))
            self.task_del.signalData.connect(self.task_del_result)
            self.task_del.start()
            self.task_del_flag = False
            
        elif y == 4:
            _id = self.tableWidget.item(x, 0).text()
            update_win = UpdateNoteWindow(self.session, _id,)
            update_win.lineEdit_title.setText(self.note_data[x]['fields']['title'])
            update_win.textBrowser.setText(self.note_data[x]['fields']['content'])
            update_win.exec()
    
    def generate_row_table(self, note):
        pass
    
    def task_get_signal_dict(self, data_dict):
        
        self.note_data = data_dict.get('data', None)
        if self.note_data is None:
            QMessageBox.information(self, '信息', '获取信息失败！', QMessageBox.Ok)
            self.task_flag = True
        else:
            self.update_page()

    def task_del_result(self, string):
        
        if  string == "ok":
            QMessageBox.information(self, '信息', '删除成功！', QMessageBox.Ok)
        else:
            QMessageBox.information(self, '信息', '删除失败！', QMessageBox.Ok)
        self.start_get_note_data()
        self.task_del_flag = True
    
class GetNoteData(QThread):
    
    signalData = Signal(dict)
    
    def __init__(self, session, url):
        super().__init__()
        self.session = session
        self.note_url = url
        self.note_data = None
    
    def run(self):

        resp = None
        
        try:
            resp = self.session.requests.get(
                self.note_url,
                cookies = self.session.session,
            )
        except Exception as e:
            self.signalData.emit(dict(err = e))
        else:
            if resp.status_code == 200:
                self.note_data = resp.content.decode()
                self.check_note_data()
            else:
                self.signalData.emit(dict(err = "error"))

    def check_note_data(self):
        ''' 检查数据 '''
        if self.note_data is None:
            self.signalData.emit(dict(err = "error"))
        else:
            try:
                self.signalData.emit(
                    dict(
                        data=json.loads(self.note_data)
                    )
                )
            except:
                self.signalData.emit(dict(err = "error"))


class DelNoteData(QThread):
    
    signalData = Signal(str)
    
    def __init__(self, session, url):
        super().__init__()
        self.session = session
        self.note_url = url
        self.note_data = None
    
    def run(self):

        resp = None
        
        try:
            resp = self.session.requests.get(
                self.note_url,
                cookies = self.session.session,
            )
        except Exception as e:
            self.signalData.emit(str(e))
        else:
            if resp.status_code == 200:
                self.signalData.emit("ok")
            else:
                self.signalData.emit("error")

if __name__ == "__main__":
    # 开始运行
    app = QApplication(sys.argv)
    winMain = MdiHomeWindow()
    winMain.show()
    # winMain.setMouseTracking(True) # 鼠标跟随
    app.exec_()